package ${projectDefinitionDO.serverProjectDefinitionDO.serverProjectStartClassPackagePathName}.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.DateDeserializers;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.DeserializationFeature;
import org.web.base.domain.config.GlobalString2DateConvert;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration("${projectDefinitionDO.serverProjectDefinitionDO.serverProjectClassNameForVariableName}JacksonConfig")
public class JacksonConfig {

    @Bean("${projectDefinitionDO.serverProjectDefinitionDO.serverProjectClassNameForVariableName}ObjectMapper")
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        // 基础配置
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 忽略null属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略未知字段
        objectMapper.registerModule(new JavaTimeModule()); // 支持Java 8时间类型

        // 自定义Date反序列化器（支持多格式）
        SimpleModule dateModule = new SimpleModule();
        dateModule.addDeserializer(Date.class, new DateDeserializers.DateDeserializer() {
            @Override
            public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                String dateStr = p.getText().trim();
                // 定义支持的日期格式列表
                String[] formats = {
                        "yyyy-MM-dd HH:mm:ss",
                        "yyyy-MM-dd",
                        "yyyy-MM-dd'T'HH:mm:ss.SSSZ", // 兼容ISO 8601格式（如前端传的2025-11-11T16:00:00.000Z）
                        "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
                };

                for (String format : formats) {
                    try {
                        return new SimpleDateFormat(format).parse(dateStr);
                    } catch (ParseException e) {
                        continue; // 格式不匹配则尝试下一个
                    }
                }
                // 若所有格式都不匹配，抛出异常（或返回null，根据需求调整）
                throw new IllegalArgumentException("Unsupported date format: " + dateStr);
            }
        });

        objectMapper.registerModule(dateModule);
        return objectMapper;
    }

    @Bean("${projectDefinitionDO.serverProjectDefinitionDO.serverProjectClassNameForVariableName}String2DateConvert")
    public GlobalString2DateConvert getGlobalString2DateConvert() {
        return new GlobalString2DateConvert();
    }

}